package com.tuling.jucdemo.hashmap;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author :tangweiliang
 * @date : 2022/12/5 23:40
 * 未来的你会感谢现在努力的自己
 *
 * trylock()与lock()区别
 * tryLock() == 不阻塞 尝试去获取锁,如果获取到了就立马返回true,否则返回false(不会阻塞)
 * lock() == 阻塞 如果不能获取锁的话就会阻塞,直到获取到锁
 *
 */
public class ReentrantLockTest {
    public static void main(String[] args) throws InterruptedException {
        final ReentrantLock reentrantLock = new ReentrantLock();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    reentrantLock.lock();
                    System.out.println("线程1获取到了锁");
                    Thread.sleep(30*1000);
                    reentrantLock.unlock();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();

        Thread.sleep(1000);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
//                    reentrantLock.lock(); // 这种写法很耗时cpu
                    while(!reentrantLock.tryLock()){
                        System.out.println("做其他的事情"); // 这种写法可以在线程1获取到了锁以后,在线程2获取锁之前,做其他的事情 new HashEntry(key,value);

                        reentrantLock.lock();

                    }
                    System.out.println("线程2获取到了锁");
                    Thread.sleep(5000);
                    reentrantLock.unlock();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();

    }
}
